﻿using Hangfire.Common;
using Hangfire.States;

namespace RuoVea.Handfire.Server;

public class EmailFailureAttribute : JobFilterAttribute, IElectStateFilter
{
    private readonly IServiceProvider _serviceProvider;

    public EmailFailureAttribute(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public void OnStateElection(ElectStateContext context)
    {
        var failedState = context.CandidateState as FailedState;
        if (failedState != null)
        {
            var emailService = _serviceProvider.GetService<EmailService>();
            if (emailService == null)
            {
                throw new InvalidOperationException("EmailService not found.");
            }

            var job = context.BackgroundJob.Job;
            var exception = failedState.Exception;

            var subject = $"Hangfire Task Failed: {job.Type.Name}";
            var body = $@"
                <h1>Hangfire Task Failed</h1>
                <p><strong>Job Type:</strong> {job.Type.Name}</p>
                <p><strong>Method Name:</strong> {job.Method.Name}</p>
                <p><strong>Exception:</strong> {exception}</p>
            ";

            emailService.SendEmailAsync("admin@example.com", subject, body).Wait();
        }
    }
}